#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : ReaderPage.py
# Purpose  : 
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-07-01 17:09
# ==============================================================================
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QWidget, QTextEdit, QHBoxLayout, QApplication, \
    QVBoxLayout
from Widgets.ReaderEdit import TextEdit
from Widgets.MiniMap import MiniMap
from Widgets.SearchBar import SearchBar
from Widgets.Highlighter import Highlighter
from conf.configuration import logger


class Frame(QWidget):

    def __init__(self, name: str = '', *args, **kwargs):
        super(Frame, self).__init__(*args, **kwargs)
        self.name = name
        self.setAcceptDrops(True)
        self.t: QTextEdit = None
        self.m: QTextEdit = None
        self.search_bar = SearchBar()  # 搜索框
        self.setup_ui()
        self.setup_signal()
        self.setObjectName('readerpage')

    #     self.installEventFilter(self)
    #
    # def eventFilter(self, a0, a1) -> bool:
    #     # if a1.type() == QEvent.InputMethod:
    #     #     logger.debug(f"dir a {dir(a1)}")
    #     logger.debug(type(a1))
    #     return super(Frame, self).eventFilter(a0, a1)

    def setup_ui(self):
        self.m = MiniMap(self.name)
        self.t = TextEdit(self.name)
        self.m.sBar.s_signal.connect(self.t.sBar.set_slider_pos)
        self.t.sBar.s_signal.connect(self.m.sBar.set_slider_pos)
        # self.t.setMaximumBlockCount(10)
        # self.m.setMaximumBlockCount(10)

        lay = QHBoxLayout(self)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.setSpacing(0)
        l_vlay = QVBoxLayout()
        l_vlay.setObjectName('vlay')
        l_vlay.setContentsMargins(0, 0, 0, 0)
        l_vlay.setSpacing(0)
        lay.addLayout(l_vlay)
        l_vlay.addWidget(self.search_bar)
        l_vlay.addWidget(self.t)
        lay.addWidget(self.m)
        self.search_bar.hide()  # 先隐藏

    def setup_signal(self):
        # self.t.cursorPositionChanged.connect(self.cursor_position_changed)
        self.t.selectionChanged.connect(self.selection_changed)  # 同步selection
        self.t.pass_key_event_signal.connect(self.m.keyPressEvent)

        self.search_bar.find_request_signal.connect(self.t.find_text)  # 发送 find text request
        self.search_bar.find_request_signal.connect(self.find_request_event)  # 发送 find text request
        self.t.n_match_pySignal.connect(self.search_bar.set_n_matches)  # n matches
        self.search_bar.search_bar_hide_signal.connect(self.t.search_bar_hide_event)  # hide search bar
        self.search_bar.search_bar_hide_signal.connect(self.search_bar_hide_event)  # hide search bar

    def search_bar_hide_event(self):
        self.m.finding_state_pySignal.emit(False)
        self.t.finding_state_pySignal.emit(False)

    def search_bar_show_event(self):
        self.search_bar.show()
        self.search_bar.find_edit.setFocus()

    def find_request_event(self, find: dict):
        self.t.finding_state_pySignal.emit(True)
        self.m.finding_state_pySignal.emit(True)
        exp = find.get('exp')
        if self.t.highlighter.find_text != exp:
            self.t.highlighter = Highlighter(self.t.document(), find_text=exp)
            self.m.highlighter = Highlighter(self.m.document(), True, find_text=exp)
            logger.debug(f"reseting highlight find text to {repr(exp)}")
            # self.t.highlighter.find_text = exp
            # self.m.highlighter.find_text = exp

    def selection_changed(self):
        """bind minimap cursor with edit cursor"""
        # self.m.setTextCursor(self.t.textCursor())
        cur_t = self.t.textCursor()
        cur_m = self.m.textCursor()
        # print(len(cur_t.document().toPlainText()), cur_t.document().toPlainText())  # debug minimap 文本长度比 edit 文本长度短短情况
        # print(len(cur_m.document().toPlainText()), cur_m.document().toPlainText())
        cur_m.setPosition(cur_t.selectionStart())
        cur_m.setPosition(cur_t.selectionEnd(), QTextCursor.KeepAnchor)
        self.m.setTextCursor(cur_m)

    def cursor_position_changed(self):
        """stop for function implemented in selection_changed"""
        pos_t = self.t.textCursor().position()
        cur_m = self.m.textCursor()
        cur_m.setPosition(pos_t)
        self.m.setTextCursor(cur_m)

    # def hideEvent(self, a0) -> None:
    #     self.close()


if __name__ == '__main__':
    from conf.configuration import style

    app = QApplication(sys.argv)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    app.setStyleSheet(style)
    frame = Frame()
    frame.show()
    sys.exit(app.exec_())
